package com.example.test.controller;

import com.example.test.entity.User;
import com.example.test.util.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;
import com.example.test.service.CacheService;

import javax.annotation.Resource;

@RestController
public class LoginController {

    @Autowired
    private ApplicationContext applicationContext;

    @Resource(name = "redis")
    private CacheService cacheService;

//    @Autowired
//    @Qualifier("mysqlDb")
    @Resource //先根据name名称或者注入类型变量名称匹配，匹配不到再根据注入类型去匹配(有多个时会报错)，都匹配不到报错
    private Db mysqlDb;

    @GetMapping("/login")
    public ResultBean login(){
        //cacheService.set("11");
//        String[] beans = applicationContext.getBeanDefinitionNames();
//        for (String bean : beans) {
//            System.out.println(bean + ": " + applicationContext.getBean(bean).getClass());
//        }
//        Db bean = (Db) applicationContext.getBean("mysqlDb1");
//        bean.select();
//        mysqlDb.select();
        return ResultBean.error(StatusCode.NOT_LOGIN.getCode(),StatusCode.NOT_LOGIN.getMsg());
    }

    @PostMapping("/loginDo")
    public ResultBean loginDo(@RequestBody User user){

//        Map map = new HashMap();
//        map.put("username","bob");
//        map.put("id","1");
//        String token = JWTUtils.createToken(map);
//        return ResultBean.success(token);
        String userName = user.getUsername();
        String password = user.getPassword();

        Subject userSubject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        try {
            // 登录验证
            userSubject.login(token);
            return ResultBean.success();
        } catch (AuthenticationException e) {
            //System.out.println(e.getMessage());
            return ResultBean.error(StatusCode.FAIL.getCode(), "用户或密码错误");
        }

    }




}
